/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import dao.ClasseDAO;
import dao.ClienteDAO;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import model.Classe;
import model.Cliente;
import model.ClientePK;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author JONATAS
 */
public class ClientesDialog extends javax.swing.JDialog {

    /**
     * Creates new form ClasseDialog
     */
    public ClientesDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnSelecionar = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cmbCampo = new javax.swing.JComboBox();
        cmbSituacao = new javax.swing.JComboBox();
        cmbCondicao = new javax.swing.JComboBox();
        tbValor1 = new javax.swing.JTextField();
        lbE = new javax.swing.JLabel();
        tbValor2 = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consulta de Clientes");
        setModalityType(java.awt.Dialog.ModalityType.DOCUMENT_MODAL);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnSelecionar.setText("Selecionar");
        btnSelecionar.setToolTipText("");
        btnSelecionar.setEnabled(false);
        btnSelecionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionarActionPerformed(evt);
            }
        });

        jButton2.setText("Imprimir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tipo Pessoa", "CPF/CNPJ/Estr", "Nome Completo", "Data Nascimento", "Endereço", "Cidade", "Projetos", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setRowSelectionAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Filtro:");

        cmbCampo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nome", "CNPJ/CPF/ID", "Cidade" }));

        cmbSituacao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ativos", "Inativos", "Todos" }));

        cmbCondicao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Contém", "Igual", "Entre", "Maior que", "Menor que" }));
        cmbCondicao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbCondicaoActionPerformed(evt);
            }
        });

        tbValor1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbValor1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbValor1KeyReleased(evt);
            }
        });

        lbE.setText("e");

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cmbCampo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmbSituacao, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(cmbCondicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tbValor1, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tbValor2, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))
                    .addComponent(btnBuscar))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbCampo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbCondicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tbValor1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tbValor2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbSituacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnSelecionar))
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(btnSelecionar))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-658)/2, (screenSize.height-582)/2, 658, 582);
    }// </editor-fold>//GEN-END:initComponents

    private void buscarTodos() {
        // Carrega todos os dados da tabela classe                 
        
        List<Cliente> lista = new ClienteDAO().findAll();
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);
        int i = 0;

        for (Cliente m : lista) {
            System.out.println("FOR");
            try {
                System.out.println("Tipo pes number-> "+m.getTipoPessoa());
                System.out.println("Tipo pes descrit-> "+m.getTipoPessoaDescricao());
                modelo.addRow(new String[]{"" + m.getTipoPessoaDescricao(), m.getCpf_cnpj(), m.getNomeCompleto(), m.getDataNascimento().toString() + "", m.getLogradouro() + ", " + m.getBairro() + ", " + m.getComplemento(), m.getCidade().getCidade_descricao(), cdao.contarProjetosDoCliente(lista.get(i)) + "", m.getStatusDescritivo() + ""});
            } catch (java.lang.NullPointerException ex) {
                System.out.println("CATCH!!!!!!!!!");
            }
            i++;
            System.out.println("i -> " + i);
        }        
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        btnBuscarActionPerformed(null);
        //buscarTodos();         
        tbValor2.setEnabled(false);
        lbE.setEnabled(false);        
    }//GEN-LAST:event_formWindowOpened

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String campo;
        String condicao;
        String situacao;
        String valor1;
        String valor2;
        switch(cmbCampo.getSelectedIndex()){
            case 0:
                campo=" upper(nomeCompleto) ";
                break;
            case 1:
                campo=" cpf_cnpj ";
                break;
            case 2:
                campo=" cidade ";
                break;        
            default: 
                campo = " upper(nomeCompleto) ";
                break;
        }
        switch(cmbCondicao.getSelectedIndex()){
            case 0:
                condicao = " like ";
                break;
            case 1:
                condicao= " = ";
                break;
            case 2: 
                condicao=" between ";
                break;                
            case 3: 
                condicao=" >= ";
                break;
            case 4: 
                condicao=" <= ";
                break;
            default:
                condicao = " like ";
                break;
        }
        switch(cmbSituacao.getSelectedIndex()){
            case 0:
                situacao = " and status = 1 ";
                break;
            case 1:
                situacao= " and status = 0 ";
                break;
            case 2:
                situacao= " and status in (0,1) ";
                break;                              
            default: 
                situacao = " and status = 1 ";
                break;
        }
        
        valor1 = tbValor1.getText().toUpperCase();
        if(condicao == " like "){
            valor1 = "%"+valor1+"%";
        }
        valor1 = "'"+valor1+"'";
        SQL = " "+campo+condicao+valor1;
        
        if(condicao == " between "){
            valor2 = " and "+"'"+tbValor2.getText().toUpperCase()+"'";
            SQL = SQL +valor2;
        }
        SQL = SQL + situacao;
        
        System.out.println("SQL -> "+SQL);  
        cdao.findCustomizado(SQL);        
        
        
        List<Cliente> lista = new ClienteDAO().findCustomizado(SQL);
        
        DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
        modelo.setNumRows(0);
        int i=0;
        for (Cliente m : lista) {
            System.out.println("FOR");
            try {
                System.out.println("Tipo pes number-> "+m.getTipoPessoa());
                System.out.println("Tipo pes descrit-> "+m.getTipoPessoaDescricao());
                modelo.addRow(new String[]{"" + m.getTipoPessoaDescricao(), m.getCpf_cnpj(), m.getNomeCompleto(), sdf.format(m.getDataNascimento()) + "", m.getLogradouro() + ", " + m.getBairro() + ", " + m.getComplemento(), m.getCidade().getCidade_descricao(), cdao.contarProjetosDoCliente(lista.get(i)) + "", m.getStatusDescritivo() + ""});
            } catch (java.lang.NullPointerException ex) {
                System.out.println("CATCH!!!!!!!!!");
            }
            i++;
            System.out.println("i -> " + i);
        }        
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void tbValor1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbValor1KeyPressed
        
    }//GEN-LAST:event_tbValor1KeyPressed

    private void tbValor1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbValor1KeyReleased
        btnBuscarActionPerformed(null);
    }//GEN-LAST:event_tbValor1KeyReleased

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        btnSelecionar.setEnabled(true);
        if (evt.getClickCount() == 2) {
            select();
        }            
    }//GEN-LAST:event_jTable1MouseClicked

    private void select(){
            int linha = jTable1.getSelectedRow();
            String tipopessoa = "" + jTable1.getValueAt(linha, 0);
            String cpfcnpj = "" + jTable1.getValueAt(linha, 1);
            
            ClientePK cpk = new ClientePK();
                                   
            cpk.setCpf_cnpj(cpfcnpj);
            cpk.setTipoPessoaByDescricao(tipopessoa);
            
            this.cliente = new Cliente();
            this.cliente = cdao.findById(cpk);
            
            this.setVisible(false);
    }
    
    private void cmbCondicaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCondicaoActionPerformed
        if(cmbCondicao.getSelectedIndex() == 2){
            tbValor2.setEnabled(true);
            lbE.setEnabled(true);
        }
        else{            
            tbValor2.setEnabled(false);            
            lbE.setEnabled(false);
        }
    }//GEN-LAST:event_cmbCondicaoActionPerformed

    private void btnSelecionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarActionPerformed
        select();
    }//GEN-LAST:event_btnSelecionarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        System.out.println("SQL para imprimir relat'orio -> where -> "+SQL);   
        
        JRBeanCollectionDataSource jrs = new JRBeanCollectionDataSource(cdao.findCustomizado(SQL));
        // Parametros
        Map parametros = new HashMap();
        parametros.put("busca", "valor filtrado");

        try {
            // Carrega o relatório para ser executado
            JasperPrint jpr = JasperFillManager.fillReport("reports/relatorio_clientes.jasper", parametros, jrs);
            // Mostra o relatório - faz o show
            JasperViewer.viewReport(jpr, false);
        } catch (JRException ex) {
            Logger.getLogger(ProjetoFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientesDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ClientesDialog dialog = new ClientesDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    private Cliente cliente = new Cliente();
    private ClienteDAO cdao = new ClienteDAO();
    String SQL;
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnSelecionar;
    private javax.swing.JComboBox cmbCampo;
    private javax.swing.JComboBox cmbCondicao;
    private javax.swing.JComboBox cmbSituacao;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel lbE;
    private javax.swing.JTextField tbValor1;
    private javax.swing.JTextField tbValor2;
    // End of variables declaration//GEN-END:variables

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }
}
